package com.baizhi.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器
 */
public class MyInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class);

    /**
     * 最先执行
     * 参数3：handler 当前请求的控制器方法对象
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.debug("=========== 1 ===========");
//        response.sendRedirect(request.getContextPath() + "/403.jsp");
//        return false;
        return true;    // true:放行，false:中断
    }

    /**
     * 参数3：handler 当前请求的控制器方法对象
     * 参数4：modelAndView 模型和试图，当前请求访问方法的modelAndView对象
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        logger.debug("=========== 2 ===========");
        logger.debug("view: {}", modelAndView.getViewName());
    }

    /**
     * 相当于finally{}代码块，无论请求正确，还是出现异常，总是执行
     * 参数3：handler 当前请求的控制器方法对象
     * 参数4：ex 如果控制器出现异常时的异常对象
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        logger.debug("=========== 3 ===========");
    }
}
